#include "addfriendswidget.h"
#include "ui_addfriendswidget.h"

#include <QDebug>
#include <QMessageBox>
#include <QByteArray>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QListWidgetItem>

#include "addfrienditem.h"
#include "friendnotificationitem.h"
#include "message.h"

AddFriendsWidget::AddFriendsWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AddFriendsWidget)
{
    ui->setupUi(this);
}

AddFriendsWidget::~AddFriendsWidget()
{
    delete ui;
}

void AddFriendsWidget::slot_receiveFriendRequest(Message message)
{
    addFriendNotificationItem(message);
}

void AddFriendsWidget::on_pushButton_search_clicked()
{
    QString username = ui->lineEdit_username->text();

    if(username.isEmpty()) {
        QMessageBox::warning(this, tr("警告"), tr("用户名不能为空"), QMessageBox::Ok);
        return;
    }

    m_request.setUrl(QUrl(m_addFriendUrl + "?username=" + username));
    m_manager.get(m_request);
    connect(&m_manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(slot_finishRequest(QNetworkReply *)));
}

void AddFriendsWidget::slot_finishRequest(QNetworkReply *reply)
{
    if (reply->error()) {
        qDebug() << "Error!";
    } else {
        // 解析reply中携带的Json
        QByteArray byteArray = reply->readAll();
        QJsonParseError jsonParseError;
        QJsonDocument parseDocument = QJsonDocument::fromJson(byteArray, &jsonParseError);
        if (jsonParseError.error == QJsonParseError::NoError) {
            if (parseDocument.isObject()) {
                QJsonObject resultJsonObject = parseDocument.object();
                qDebug() <<__FILE__ << __LINE__ << __FUNCTION__ << "result =" << QString(QJsonDocument(resultJsonObject).toJson());
                if (resultJsonObject.contains("success")) {
                    bool isSuccess = resultJsonObject.value("success").toBool();
                    if (isSuccess) {
                        QJsonObject userJsonObject = resultJsonObject.value("data").toObject();
                        addFriendItem(userJsonObject.value("username").toString(), userJsonObject.value("id").toString());
                    } else {
                        QMessageBox::critical(this, "失败", resultJsonObject.value("message").toString(), QMessageBox::Ok);
                        ui->lineEdit_username->setFocus();
                    }
                }
            }
        }
    }

    reply->deleteLater();
}

void AddFriendsWidget::slot_friendRequest(Message message)
{
    emit signal_friendRequest(message);
}

void AddFriendsWidget::slot_agreeFriendRequest(QString fromId)
{

    QJsonObject jsonObj;
    jsonObj.insert("userId", m_userId);
    jsonObj.insert("friendId", fromId);

    qDebug() << __FILE__ <<__LINE__ << __FUNCTION__ << QString(QJsonDocument(jsonObj).toJson());

    QJsonDocument jsonDoc;
    jsonDoc.setObject(jsonObj);

    QByteArray data = jsonDoc.toJson(QJsonDocument::Compact);

//    m_request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    m_request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    m_request.setUrl(QUrl(m_addFriendUrl));

    m_manager.post(m_request, data);
    connect(&m_manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(slot_agreeFriendRequestReply(QNetworkReply *)));
}

void AddFriendsWidget::slot_agreeFriendRequestReply(QNetworkReply *reply)
{
    qDebug() << __FILE__ << __LINE__ << __FUNCTION__;
    if (reply->error()) {
        qDebug() << "Error!";
        QMessageBox::warning(this, tr("登录失败"), tr("请检查网络连接"), QMessageBox::Ok);
    } else {
        // 解析reply中携带的Json
        QByteArray byteArray = reply->readAll();
        QJsonParseError jsonParseError;
        QJsonDocument parseDocument = QJsonDocument::fromJson(byteArray, &jsonParseError);
        if (jsonParseError.error == QJsonParseError::NoError) {
            if (parseDocument.isObject()) {
                QJsonObject resultJsonObject = parseDocument.object();
                qDebug() <<__FILE__ << __LINE__ << __FUNCTION__ << "result =" << QString(QJsonDocument(resultJsonObject).toJson());
                if (resultJsonObject.contains("success")) {
                    bool isSuccess = resultJsonObject.value("success").toBool();
                    if (isSuccess) {
                        qDebug() << __FILE__ << __LINE__ << __FUNCTION__;
                        emit signal_addFriendSuccess(resultJsonObject.value("data").toObject());
                    } else {
                        QMessageBox::critical(this, "失败", resultJsonObject.value("message").toString(), QMessageBox::Ok);
                    }
                }
            }
            qDebug() << __FILE__ << __LINE__ << __FUNCTION__ << jsonParseError.errorString();
        }
        qDebug() << __FILE__ << __LINE__ << __FUNCTION__;
    }

    reply->deleteLater();
}

QString AddFriendsWidget::userId() const
{
    return m_userId;
}

void AddFriendsWidget::setUserId(const QString &newUserId)
{
    m_userId = newUserId;
}

void AddFriendsWidget::addFriendItem(QString username, QString userId)
{
    AddFriendItem *addFriendItem = new AddFriendItem;
    addFriendItem->setUserId(userId);
    addFriendItem->setUsername(username);

    QListWidgetItem *listWidgetItem = new QListWidgetItem;
    ui->listWidget_friends->insertItem(0, listWidgetItem);
    ui->listWidget_friends->setItemWidget(listWidgetItem, addFriendItem);

    connect(addFriendItem, &AddFriendItem::signal_friendRequest, this, &AddFriendsWidget::slot_friendRequest);
}

void AddFriendsWidget::addFriendNotificationItem(Message message)
{
    FriendNotificationItem *friendNotificationItem = new FriendNotificationItem;
    friendNotificationItem->setFromId(message.fromId());
    friendNotificationItem->setUsername(message.fromId());
    friendNotificationItem->setType("向您发送好友请求");
    friendNotificationItem->setTimestamp(message.timestamp());

    QListWidgetItem *listWidgetItem = new QListWidgetItem;
    ui->listWidget_friendNotifications->insertItem(0, listWidgetItem);
    ui->listWidget_friendNotifications->setItemWidget(listWidgetItem, friendNotificationItem);

    connect(friendNotificationItem, &FriendNotificationItem::signal_agreeFriendRequest, this, &AddFriendsWidget::slot_agreeFriendRequest);
}

